package projectmanagement.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import projectmanagement.model.Person;
import projectmanagement.util.ApplicationSecurityManager;
import projectmanager.model.dao.PersonDao;

public class SignInController extends SimpleFormController {

	private PersonDao personManager;
	private ApplicationSecurityManager applicationSecurityManager;

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		return new Person();
	}

	public ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors, Map controlModel)
			throws Exception {
		if (applicationSecurityManager.getPerson(request) != null)
			return new ModelAndView(getSuccessView());

		return super.showForm(request, response, errors, controlModel);
	}

	/**
	 * Atliekamas prisijungimo vardo ir slaptazodzio validavimas.
	 * 
	 */
	public void onBindAndValidate(HttpServletRequest request, Object command,
			BindException errors) throws Exception {

		if (errors.hasErrors())
			return;

		Person formPerson = (Person) command;
		Person dbPerson = personManager.getPersonByUsername(formPerson.getUsername());
		if (dbPerson == null || !dbPerson.getPassword().equals(formPerson.getPassword())){
			errors.reject("error.login.invalid");
		}
		else {
			 applicationSecurityManager.setPerson(request, dbPerson);
		}
	}

	public ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		return new ModelAndView(getSuccessView());
	}

	public PersonDao getPersonManager() {
		return personManager;
	}

	public void setPersonManager(PersonDao personManager) {
		this.personManager = personManager;
	}

	public ApplicationSecurityManager getApplicationSecurityManager() {
		return applicationSecurityManager;
	}

	public void setApplicationSecurityManager(
			ApplicationSecurityManager applicationSecurityManager) {
		this.applicationSecurityManager = applicationSecurityManager;
	}

}
